package com.kunyi.web.service.file.application.controller;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.kunyi.platform.auth.ThreadLocalAuth;
import com.kunyi.platform.tool.api.JsonResult;
import com.kunyi.platform.tool.util.KyAssertUtil;
import com.kunyi.web.service.file.core.handel.KunyiFileHandelContxt;
import com.kunyi.web.service.file.core.handel.KunyiRepository;
import com.kunyi.web.service.file.entity.domain.Upload;
import com.kunyi.web.service.file.service.IUploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * @ClassName FileController
 * @Description 文件-接口
 * @Author pengjunjun
 * @Date 2024/03/04
 * @Version 1.0
 **/
@Slf4j
@Api(tags = "文件-接口")
@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    private IUploadService uploadService;
    @Autowired
    private KunyiFileHandelContxt kunyiFileHandelContxt;
    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public JsonResult<String> upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return JsonResult.error("请选择您要上传的文件");
        }
        if(ThreadLocalAuth.getTenantId() == null){
            ThreadLocalAuth.setTenantId(0L);
        }
        //获得对应的处理类
        KunyiRepository kunyiRepository = kunyiFileHandelContxt.handel();
        String src = kunyiRepository.uploadMultipartFile(file);
        return JsonResult.success(src);
    }

    @ApiOperation("获取文件")
    @Mapping("/view/{fileName}")
    public void index(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {
        String tenantId = fileName.split("_")[0];
        Boolean isNumber = NumberUtil.isNumber(tenantId);
        KyAssertUtil.isTrue(isNumber,"文件名不合法");
        ThreadLocalAuth.setTenantId(Long.valueOf(tenantId));
        Upload upload = uploadService.getByFileName(fileName);
        KyAssertUtil.notNull(upload,"没有该文件！！！");
        if (StrUtil.isNotBlank(upload.getMimeType())) {
            response.setContentType(upload.getMimeType());
        }
        KunyiRepository kunyiRepository = kunyiFileHandelContxt.handel();
        // 获取输入流、输出流
        try (InputStream is = kunyiRepository.readStream(upload.getName()); ServletOutputStream os = response.getOutputStream()) {
            response.setCharacterEncoding("UTF-8");
            // 将文件内容写入响应输出流
            byte[] buffer = new byte[1024]; // 缓冲
            int length;
            while ((length = is.read(buffer)) != -1) {
                os.write(buffer, 0, length);
            }
        }
    }
}
